package cn.maydaymemory.mastery.shop;

import cn.maydaymemory.mastery.PluginMastery;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.io.File;
import java.util.*;

public class Shop {
    private static List<String> goodsListEditor = new ArrayList<>();
    private static List<String> goodsListViewer = new ArrayList<>();
    private static ArrayList<ItemStack> items = new ArrayList<>();

    public static class Currency{
        private static Map<String,Currency> currencyMap = new HashMap<>();
        ItemStack item;
        int rank;
        Currency(ItemStack _item , int _rank){
            item = _item;
            rank=_rank;
        }
        public ItemStack getItem(){return item;}
        public int getRank(){return rank;}
    }

    public static class Price{
        String type;
        int price;
        public Price(String _type, int _price){
            type = _type;
            price=_price;
        }
        public String getType(){return type;}
        public int getPrice(){return price;}
        public Price clone(){
            return new Price(type,price);
        }
    }

    private static Map<ItemStack,Price> goods = new HashMap<>();

    public static List<Inventory> goodsInventoryList = new ArrayList<>();

    public static List<ItemStack> getGoodsList(){
        return new ArrayList<>(goods.keySet());
    }

    public static void refreshGoods(){
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig  = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        goods = new HashMap<>();
        for(String key: goodsConfig.getKeys(false)){
            ItemStack good = goodsConfig.getItemStack(key+".item");
            String type = goodsConfig.getString(key+".type");
            int price = goodsConfig.getInt(key+".price");
            int amount = goodsConfig.getInt(key+".amount");
            if(good != null&&type != null){
                good.setAmount(amount);
                goods.put(good,new Price(type,price));
            }
        }
        goodsInventoryList = getGoodsListInventory(null);
    }

    public static void deleteGoods(ItemStack good){
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig  = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        ItemStack del=null;
        for(ItemStack key:goods.keySet()){
            if(key.isSimilar(good)) {del = key; break;}
        }
        if(del!=null) goods.remove(del);
        for(String key:goodsConfig.getKeys(false)){
            ItemStack item = goodsConfig.getItemStack(key+".item");
            if(item==null) continue;
            if(item.isSimilar(good)) {
                goodsConfig.set(key,null);
            }
        }
        PluginMastery.getInstance().getConfigManager().save(fileGoodsConfig);
        goodsInventoryList = getGoodsListInventory(null);
    }

    public static int getInventoryIndex(Inventory inv){
        return goodsInventoryList.indexOf(inv);
    }

    public static void deleteGoods(int index){
        deleteGoods(items.get(index));
    }

    public static void setGoods(ItemStack good,Price price){
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig  = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        ItemStack edit = null;
        for(ItemStack item :goods.keySet()){
            if(item.isSimilar(good))  {
                edit = item; break;
            }
        }
        if(edit!=null)  {
            goods.remove(edit);
        }
        goods.put(good,price);
        String uuid= UUID.randomUUID().toString();
        for(String key:goodsConfig.getKeys(false)){
            ItemStack item = goodsConfig.getItemStack(key+".item");
            if(item==null) continue;
            if(item.isSimilar(good)) uuid=key;
        }
        goodsConfig.set(uuid+".item",good);
        goodsConfig.set(uuid+".amount",good.getAmount());
        goodsConfig.set(uuid+".price",price.getPrice());
        goodsConfig.set(uuid+".type",price.getType());
        PluginMastery.getInstance().getConfigManager().save(fileGoodsConfig);
        goodsInventoryList = getGoodsListInventory(null);
    }

    public static Price getPrice(ItemStack good){
        for(ItemStack k : goods.keySet()){
            if(k.isSimilar(good)) {
                if(goods.get(k)==null) continue;
                Price price = goods.get(k).clone();
                int alpha = good.getAmount()/k.getAmount();
                price.price = price.price*alpha;
                return price;
            }
        }
        return null;
    }

    public static ArrayList<String> getCurrencyList(){
        return new ArrayList<>(Currency.currencyMap.keySet());
    }

    public static Currency getCurrency(String name){
        return Currency.currencyMap.get(name);
    }

    public static void setCurrency(ItemStack currency,String name,int rank){
        if(name.equals("vault")) return;
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        goodsConfig.set("currency."+name+".rank",rank);
        goodsConfig.set("currency."+name+".item",currency);
        PluginMastery.getInstance().getConfigManager().save(fileGoodsConfig);
        Currency.currencyMap.put(name,new Currency(currency,rank));
    }

    public static void deleteCurrency(String name){
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        goodsConfig.set("currency."+name,null);
        PluginMastery.getInstance().getConfigManager().save(fileGoodsConfig);
        Currency.currencyMap.remove(name);
    }

    private static class CurrencyCamp implements Comparator<String>{
        @Override
        public int compare(String o1, String o2) {
            int i1 = 0;
            int i2 = 0;
            if(getCurrency(o1)!=null) i1 = getCurrency(o1).getRank();
            if(getCurrency(o2)!=null) i2 = getCurrency(o2).getRank();
            return i2-i1;
        }
    }

    public static ArrayList<String> getCurrencySequence(){
        ArrayList<String> list = getCurrencyList();
        list.sort(new CurrencyCamp());
        return list;
    }

    public static void refreshCurrency(){
        File fileGoodsConfig = new File(PluginMastery.getInstance().getDataFolder(),"goods.yml");
        FileConfiguration goodsConfig  = PluginMastery.getInstance().getConfigManager().getConfig(fileGoodsConfig);
        Currency.currencyMap = new HashMap<>();
        ConfigurationSection section = goodsConfig.getConfigurationSection("currency");
        if(section==null) return;
        for(String key: section.getKeys(false)){
            if(key.equals("vault")) continue;
            ItemStack item = section.getItemStack(key+".item");
            int rank = section.getInt(key+".rank");
            if(item == null) continue;
            Currency.currencyMap.put(key,new Currency(item,rank));
        }
    }

    public static void editGoodsList(HumanEntity player){
        if(goodsInventoryList.isEmpty()) return;
        if(!goodsListEditor.contains(player.getName())) goodsListEditor.add(player.getName());
        player.openInventory(goodsInventoryList.get(0));
    }
    public static void editGoodsList(HumanEntity player,int index){
        if(goodsInventoryList.isEmpty()) return;
        if(!goodsListEditor.contains(player.getName())) goodsListEditor.add(player.getName());
        player.openInventory(goodsInventoryList.get(index));
    }

    public static boolean isGoodsListEditor(HumanEntity player){
        return goodsListEditor.contains(player.getName());
    }

    public static void stopGoodsListEdit(HumanEntity player){
        goodsListEditor.remove(player.getName());
    }

    public static void viewGoodsList(HumanEntity player){
        if(goodsInventoryList.isEmpty()) return;
        if(!goodsListViewer.contains(player.getName())) goodsListViewer.add(player.getName());
        player.openInventory(goodsInventoryList.get(0));
    }

    public static void viewGoodsList(HumanEntity player,int index){
        if(goodsInventoryList.isEmpty()) return;
        if(!goodsListViewer.contains(player.getName())) goodsListViewer.add(player.getName());
        player.openInventory(goodsInventoryList.get(index));
    }

    public static boolean isGoodsListViewer(HumanEntity player){
        return goodsListViewer.contains(player.getName());
    }

    public static void stopGoodsListView(HumanEntity player){
        goodsListViewer.remove(player.getName());
    }

    private static class Camp implements Comparator<ItemStack>{
        @Override
        public int compare(ItemStack o1, ItemStack o2) {
            return o1.getType().compareTo(o2.getType());
        }
    }

    private static List<Inventory> getGoodsListInventory(InventoryHolder owner){
        items = new ArrayList<>(goods.keySet());
        items.sort(new Camp());
        List<Inventory> list = new ArrayList<>();
        File fileConfig = new File(PluginMastery.getInstance().getDataFolder(),"config.yml");
        FileConfiguration config = PluginMastery.getInstance().getConfigManager().getConfig(fileConfig);
        Inventory inventory = Bukkit.createInventory(owner,36,PluginMastery.getInstance().getCurrent_lang().getString("inventory1")+"");
        int count = 0;
        for(ItemStack good:items){
            Price price = getPrice(good);
            if(price== null) continue;
            if(count==27) {
                if(list.size()>0){
                    list.get(list.size()-1).setItem(35,config.getItemStack("button_next"));
                    inventory.setItem(27,config.getItemStack("button_front"));
                }
                list.add(inventory);
                inventory = Bukkit.createInventory(owner,36,PluginMastery.getInstance().getCurrent_lang().getString("inventory1")+"");
                count=0;
            }
            ItemStack copy = good.clone();
            List<String> lore = new ArrayList<>();
            if(copy.getItemMeta()!=null&&copy.getItemMeta().getLore()!=null) lore = copy.getItemMeta().getLore();
            Economy econ = PluginMastery.getInstance().getEcon();
            if( price.getType().equalsIgnoreCase("vault")&&econ == null){
                lore.add("§d§e§f"+PluginMastery.getInstance().getCurrent_lang().getString("non-value"));
            }else {
                for (String str : PluginMastery.getInstance().getCurrent_lang().getStringList("lore")) {
                    if (price.getType().equalsIgnoreCase("vault"))
                        lore.add("§d§e§f" + str.replaceAll("%price%", price.getPrice() + "").replaceAll("%type%", econ.currencyNamePlural()));
                    else
                        lore.add("§d§e§f" + str.replaceAll("%price%", price.getPrice() + "").replaceAll("%type%", price.getType()));
                }
            }
            if(copy.getItemMeta()!=null){
                ItemMeta meta = copy.getItemMeta();
                meta.setLore(lore);
                copy.setItemMeta(meta);
            }
            inventory.setItem(count,copy);
            count++;
        }
        if(list.size()>0){
            inventory.setItem(27,config.getItemStack("button_front"));
            list.get(list.size()-1).setItem(35,config.getItemStack("button_next"));
        }
        list.add(inventory);
        return list;
    }
}
